package com.itbaizhan.rocketmqproducer.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.List;

//全局顺序消息
public class GlobalOrderProducer {
    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer producer = new DefaultMQProducer("producer_grp_01");
        producer.setNamesrvAddr("192.168.66.100:9876");
        producer.start();

        Message message = null;
        for(int i=0;i<2;i++){
            //创建消息
            message = new Message("topic_springboot_01",("全局消息。。。"+i).getBytes(RemotingHelper.DEFAULT_CHARSET));
            //发送消息
            producer.send(message, new MessageQueueSelector() {
              // select方法第一个参数: 指该Topic下有的队列集合
        // 第二个参数: 发送的消息(消息的对象)
        // 第三个参数: （队列id）消息将要进入的队列下标，它与send方法的第三个参数相同
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    return list.get((Integer)o); //o 也可以换为0
                }},1);
        }
        producer.shutdown();
    }

}
